package cfg

import (
	"fmt"
	"os"
	"strings"

	"github.com/gookit/ini/v2"
)

func LoadConfig(cfgFile string) (name, path, logFile string, links []string, convertToJPG, crop, scale, square, override, localSave bool) {
    err := ini.LoadExists(cfgFile)
    if err != nil {
        panic(fmt.Sprintf("Failed to load ini file:\n%v\n", err))
    }

    name = ini.String("name")
    path = ini.String("path")
    logFile = ini.String("logFile")
    links, err = ParseFileURLs(ini.String("links"))
    if err != nil {
        panic(fmt.Sprintf("Failed to parse urls:\n%v\n", err))
    }

    convertToJPG = ini.Bool("convertToJPG")
    crop = ini.Bool("crop")
    scale = ini.Bool("scale")
    square = ini.Bool("square")
    override = ini.Bool("override")
    localSave = ini.Bool("localSave")
    return
}

func ParseFileURLs(urlStr string) (urlList []string, err error) {
    file, err := os.ReadFile(urlStr)
    if err != nil {
        return nil, err
    }
    urlList = strings.Split(string(file), "\n")

    if urlList[len(urlList)-1] == "" {
        urlList = urlList[:len(urlList)-1]
    }

    for i, item := range urlList {
        urlList[i], _ = strings.CutSuffix(item, "\r") // гулаг + вин момент
    }
    return
}
